package business.validation;

import java.util.Iterator;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;


public class BusinessValidatorImpl<E> implements BusinessValidator<E>{
	
	public void validate(E elementToValidate) throws ValidationException {
		
		javax.validation.Validator validator = Validation.buildDefaultValidatorFactory().getValidator();			
		Set<ConstraintViolation<E>> violations = validator.validate(elementToValidate);
		if (violations.size()>0) {
			StringBuilder sbuilder = new StringBuilder();
			Iterator<ConstraintViolation<E>> it = violations.iterator();
			
			sbuilder.append("Invalid values: ");
			while (it.hasNext()) {
				ConstraintViolation<E> currentViolation = it.next();
				sbuilder.append("Invalid value: " + currentViolation.getInvalidValue() +
								" - " + currentViolation.getMessage() + "\n");
			}
			throw new ValidationException(sbuilder.toString());
		}		
	}
}
